﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public abstract class Bugtracker
    {
        protected SettingsManager settings_ = null;

        protected ProgressCallback progress_callback_ = null;
        protected TestCallback success_callback_ = null;
        protected TestCallback fail_callback_ = null;

        protected string[] validation_steps_texts_ = null;

        protected Bugtracker(SettingsManager settings)
        {
            settings_ = settings;
        }

        public bool ValidateSettings()
        {
            SetSteps();
            return ValidateSettings(new RunTestCallback(RunCurrentStep));
        }

        public bool ValidateSettings(RunTestCallback run_test)
        {
            int totalStep = validation_steps_texts_.Length;

            int current_step = 0;

            try
            {
                for (; current_step < totalStep; ++current_step)
                {
                    UpdateProgress(validation_steps_texts_[current_step], current_step, totalStep);

                    if (!run_test(current_step))
                        break;

                    TestSuccess(current_step);
                }
            }
            catch { }

            if (current_step < totalStep)
            {
                TestFail(current_step);
                UpdateProgress(string.Format("{0} - {1}", validation_steps_texts_[current_step], Common.Resources.CommonResources.Failed), current_step + 1, totalStep);
                return false;
            }

            UpdateProgress("Done.", totalStep, totalStep);
            return true;
        }

        protected abstract void SetSteps();
        protected abstract bool RunCurrentStep(int current_step);

        public void RegisterProgressCallback(Common.ProgressCallback callback)
        {
            progress_callback_ = callback;
        }

        public void RegisterTestCallback(Common.TestCallback success_callback, Common.TestCallback fail_callback)
        {
            success_callback_ = success_callback;
            fail_callback_ = fail_callback;
        }

        protected void UpdateProgress(String step, int currentStep, int totalStep)
        {
            if (progress_callback_ != null)
                progress_callback_(step, currentStep, totalStep);
        }

        protected void TestSuccess(int currentStep)
        {
            if (success_callback_ != null)
                success_callback_(currentStep);
        }

        protected void TestFail(int currentStep)
        {
            if (fail_callback_ != null)
                fail_callback_(currentStep);
        }
    }
}
